package  org.jeecg.modules.hotel.check.controller;


import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;


import org.jeecg.modules.basic.demo.bed.entity.LwgyBaseBed;
import org.jeecg.modules.basic.demo.bed.service.ILwgyBaseBedService;
import org.jeecg.modules.hotel.arrangement.service.ILwgyHotelArrangementService;
import org.jeecg.modules.hotel.history.entity.LwgyHotelHistory;
import org.jeecg.modules.hotel.history.service.ILwgyHotelHistoryService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.hotel.check.entity.TestB;
import org.jeecg.modules.hotel.check.entity.Repeat;
import  org.jeecg.modules.hotel.check.vo.checkPage;
import  org.jeecg.modules.hotel.check.service.IcheckService;
import  org.jeecg.modules.hotel.check.service.ITestBService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 重复住宿校验
 * @Author: jeecg-boot
 * @Date:   2021-04-26
 * @Version: V1.0
 */
@Api(tags="重复住宿校验")
@RestController
@RequestMapping("/org.jeecg.modules.hotel/check")
@Slf4j
public class checkController {
	@Autowired
	private IcheckService checkService;
	@Autowired
	private ITestBService testBService;
	 @Autowired
	 private ILwgyHotelArrangementService lwgyHotelArrangementService;
	 @Autowired
	 private ILwgyHotelHistoryService lwgyHotelHistoryService;
	 @Autowired
	 private ILwgyBaseBedService iLwgyBaseBedService;
	 @Autowired
	 private ILwgyBaseBedService lwgyBaseBedService;

	
	/**
	 * 分页列表查询
	 *
	 * @param check
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
/*	@AutoLog(value = "重复住宿校验-分页列表查询")
	@ApiOperation(value="重复住宿校验-分页列表查询", notes="重复住宿校验-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(check check,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<check> queryWrapper = QueryGenerator.initQueryWrapper(check, req.getParameterMap());
		Page<check> page = new Page<check>(pageNo, pageSize);
		IPage<check> pageList = checkService.page(page, queryWrapper);
		System.out.println("pageList:"+pageList);
		return Result.OK(pageList);
	}
	*/
	/**
	 *   添加
	 *
	 * @param checkPage
	 * @return
	 */
	@AutoLog(value = "重复住宿校验-添加")
	@ApiOperation(value="重复住宿校验-添加", notes="重复住宿校验-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody checkPage checkPage) {
		Repeat check = new Repeat();
		BeanUtils.copyProperties(checkPage, check);
		checkService.saveMain(check, checkPage.getTestBList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param checkPage
	 * @return
	 */
	@AutoLog(value = "重复住宿校验-编辑")
	 @ApiOperation(value="重复住宿校验-编辑", notes="重复住宿校验-编辑")
	 @PutMapping(value = "/edit")
	 public Result<?> edit(@RequestBody checkPage checkPage) {
		 Repeat check = new Repeat();
		 BeanUtils.copyProperties(checkPage, check);
		 Repeat checkEntity = checkService.getById(check.getId());
		 if(checkEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 checkService.updateMain(check, checkPage.getTestBList());
		 return Result.OK("编辑成功!");
	 }
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "重复住宿校验-通过id删除")
	@ApiOperation(value="重复住宿校验-通过id删除", notes="重复住宿校验-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		checkService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
/*	@AutoLog(value = "重复住宿校验-批量删除")
	@ApiOperation(value="重复住宿校验-批量删除", notes="重复住宿校验-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.checkService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}*/
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "重复住宿校验-通过id查询")
	@ApiOperation(value="重复住宿校验-通过id查询", notes="重复住宿校验-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Repeat check = checkService.getById(id);
		if(check==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(check);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "重复校验的住宿信息通过主表ID查询")
	@ApiOperation(value="重复校验的住宿信息主表ID查询", notes="重复校验的住宿信息-通主表ID查询")
	@GetMapping(value = "/queryTestBByMainId")
	public Result<?> queryTestBListByMainId(@RequestParam(name="id",required=true) String id) {
		List<TestB> testBList = testBService.selectByMainId(id);
		return Result.OK(testBList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param check
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Repeat check) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<Repeat> queryWrapper = QueryGenerator.initQueryWrapper(check, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      //List<Repeat> queryList = checkService.list(queryWrapper);
		List<Repeat> queryList = checkService.checkRepeatCwList(queryWrapper);
		System.out.println(queryList);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<Repeat> checkList = new ArrayList<Repeat>();
      if(oConvertUtils.isEmpty(selections)) {
          checkList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          checkList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<checkPage> pageList = new ArrayList<checkPage>();
      for (Repeat main : checkList) {
          checkPage vo = new checkPage();
          BeanUtils.copyProperties(main, vo);
          List<TestB> testBList = testBService.selectByMainId(main.getId());
          vo.setTestBList(testBList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "重复住宿校验列表");
      mv.addObject(NormalExcelConstants.CLASS, checkPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("重复住宿校验数据", "导出人:"+sysUser.getRealname(), "重复住宿校验"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }


/**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    *//*

    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<checkPage> list = ExcelImportUtil.importExcel(file.getInputStream(), checkPage.class, params);
              for (checkPage page : list) {
                  Repeat po = new Repeat();
                  BeanUtils.copyProperties(page, po);
                  checkService.saveMain(po, page.getTestBList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }
*/



	 /**
	  * 分页列表查询
	  *
	  * @param check
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "重复住宿校验-分页列表查询")
	 @ApiOperation(value="重复住宿校验-分页列表查询", notes="重复住宿校验-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<?> end(Repeat check,
						  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
						  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
						  HttpServletRequest req) {
	 	System.out.println("-----:"+req.getParameterMap());
		 /*条件构造器 表单分页*/
		 QueryWrapper<Repeat> queryWrapper = QueryGenerator.initQueryWrapper(check, req.getParameterMap());
		 Page<Repeat> page = new Page<Repeat>(pageNo, pageSize);
		 /*条件构造器 表单分页*/

		 IPage<Repeat> queryList = checkService.checkRepeatCw(page, queryWrapper);
		 System.out.println(queryList);
		 return Result.OK(queryList);
	 }


	/**
	  *  批量退宿,通过student_id清理学生
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "重复住宿校验-按照学生id批量退宿")
	 @ApiOperation(value="重复住宿校验-按照学生id批量退宿", notes="重复住宿校验-按照学生id批量退宿")
	 @GetMapping(value = "/batchLeaveBed")
	 public Result<?> batchLeaveBed(@RequestParam(name="studentIds",required=true) String studentIds) {

	 	System.out.println("=============:"+studentIds);
	 	//按照学生id获取所有住宿信息
		 List<LwgyBaseBed> list =iLwgyBaseBedService.getBedListByStuId(studentIds.split(","));
		 System.out.println(list);
		 // this.checkService.delBatchMain(Arrays.asList(ids.split(",")));
		 List<LwgyHotelHistory> arrangementList = new ArrayList<>();
		 String ids = "";

		 for (int i=0;i< list.size();i++) {
			 LwgyBaseBed iwgyBaseBed =  list.get(i);
			 ids += iwgyBaseBed.getId() + ",";
			 LwgyHotelHistory lwgyHotelHistory = new LwgyHotelHistory();
			 lwgyHotelHistory.setPersonId(iwgyBaseBed.getStudentId());
			 lwgyHotelHistory.setBeforeBed(iwgyBaseBed.getId());
			 lwgyHotelHistory.setBehavior("leave_bed");
			// lwgyHotelHistory = JSON.parseObject(JSON.toJSONString(iwgyBaseBed), LwgyHotelHistory.class);
			 arrangementList.add(lwgyHotelHistory);
		 }
		 lwgyHotelArrangementService.cleanBed(ids);//批量清空住宿
		 lwgyHotelHistoryService.saveBatch(arrangementList);//批量存储退宿记录


		 return Result.OK("批量退宿成功！");
	 }

	 /**
	  *  退掉重复住宿
	  *
	  * @param checkPage
	  * @return
	  */
	 @AutoLog(value = "重复住宿校验-编辑")
	 @ApiOperation(value="重复住宿校验-编辑", notes="重复住宿校验-编辑")
	 @PutMapping(value = "/deletion")
	 public Result<?> deletion(@RequestBody checkPage checkPage) {
		 try {
			 //获取checkpage 中正确的
			 List<TestB> list = checkPage.getTestBList();
			 if (list.size() > 1) {
				 return Result.error("每个学生只能保留一个床位");
			 }
			 String trueId = list.get(0).getId();
			 String studentId = list.get(0).getStudentId();
			 System.out.println("trueId:" + trueId + "studentId:" + studentId);
			 QueryWrapper<LwgyBaseBed> queryWrapper = new QueryWrapper();
			 queryWrapper.eq("student_id", studentId);
			 queryWrapper.ne("id", trueId);
			 List<LwgyBaseBed> bedList = lwgyBaseBedService.list(queryWrapper);
			 String tsIds = "";
			 String tsStuIds = "";


			 for (LwgyBaseBed item : bedList) {

				 lwgyHotelArrangementService.cleanBed(item.getId());//批量清空住宿
				 //2. 存储到历史记录
				 LwgyHotelHistory lwgyHotelHistory = new LwgyHotelHistory();
				 lwgyHotelHistory.setBeforeBed(item.getId());
				 lwgyHotelHistory.setBehavior("leave_bed");
				 lwgyHotelHistory.setPersonId(item.getStudentId());
				 lwgyHotelHistory.setSort("");
				 lwgyHotelHistoryService.save(lwgyHotelHistory);

			 }

			 return Result.OK("编辑成功!");
		 } catch (Exception e) {
			 return Result.error("编辑报错!"+e);
		 }
	 }
 }
